package com.qsl.ssyx.acl.util;

import com.qsl.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

public class PermissionHelper {


    //
    public static List<Permission> buildPermission(List<Permission> allPermissionList) {
        List<Permission> trees = new ArrayList<>();
        // 遍历并查询第1层数据
        for (Permission permission : allPermissionList) {

            if (permission.getPid() == 0) { // 第1层数据
                permission.setLevel(1); // 层级

                // 根据id判断是否有下一层数据
                trees.add(isChildren(permission, allPermissionList));
            }
        }
        return trees;
    }

    // 递归查询
    private static Permission isChildren(Permission permission, List<Permission> allPermissionList) {
        permission.setChildren(new ArrayList<Permission>());
        // 遍历菜单所有数据
        for (Permission i : allPermissionList) {
            // 判断 Id == pid
            if (permission.getId().longValue() == i.getPid().longValue()) {
                int level = permission.getLevel() + 1;
                i.setLevel(level); // 层级
                if (permission.getChildren() == null) {
                    permission.setChildren(new ArrayList<>());
                }
                // 封装下一层数据
                permission.getChildren().add(isChildren(i, allPermissionList));
            }
        }
        return permission;
    }
}
